import {
  login,
  logout,
  getInfo
} from "@/api/user"
import {
  getStorageItem,
  setStorageItem,
  removeStorageItem,
} from "@/utils/storage.js"

import {
  Token,
  UserInfo
} from "@/utils/constant"

const state = {
  token: getStorageItem(Token) || "",
  user: getStorageItem(UserInfo) || {},
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },

  SET_USER: (state, user) => {
    state.user = user
  },
}

const actions = {
  // set user info
  setInfo({
    commit
  }, res) {
    commit("SET_TOKEN", res.token)
    commit("SET_USER", res.userInfoVO)
    setStorageItem(Token, res.token)
    setStorageItem(UserInfo, res.userInfoVO)
  },

  setUser({
    commit
  }, user) {
    commit("SET_USER", user)
    setStorageItem(UserInfo, user)
  },

  // user login
  login({
    commit
  }, userInfo) {
    const {
      username,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
          username: username.trim(),
          password: password,
        })
        .then((response) => {
          const {
            data
          } = response
          commit("SET_TOKEN", data.token)
          commit("SET_USER", data)
          setStorageItem(Token, data.token)
          setStorageItem(UserInfo, data)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({
    commit,
  }) {
    commit("SET_TOKEN", "")
    commit("SET_USER", {})
    removeStorageItem(Token)
    removeStorageItem(UserInfo)
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "")
      removeStorageItem(Token)
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
